<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
    </style>
</head>
<body>
    用户名：<input type="text" id="username"><br>
    密码：<input type="text" id="password"><br>
    <input type="button" value="登录" id="btn1">
    <input type="button" value="注册" id="btn2">
    <input type="button" value="获取" id="btn3">
</body>
<script>
    
    const oun = document.getElementById("username")
    const opw = document.getElementById("password")
    const ob1 = document.getElementById("btn1")
    const ob2 = document.getElementById("btn2")
    const ob3 = document.getElementById("btn3")

    ob1.onclick = function(){
        // 发起登录请求，携带数据
        ajaxGet({
            url: "http://localhost:3000/login",
            data:{
                username: oun.value,
                password: opw.value
            },
            success:res=>{
                console.log(res);
            },
            error:code=>{
                console.log(code);
            }
        })
    }

    function ajaxGet(ops = {}){
        let {type="get", success, error, data={}, url} = ops;
        // 1. 将对象数据处理成query数据
        let str = "";
        for(let i in data){
            str += `${i}=${data[i]}&`;
        }
        // 2. 拼接到url
        url += "?" + str.slice(0,-1);
        // 3. 创建ajax请求
        const xhr = new XMLHttpRequest();
        xhr.open(type, url, true);
        xhr.onreadystatechange = function(){
            console.log(xhr.status);
            if(xhr.readyState === 4 && xhr.status === 200){
                success(xhr.responseText);
            }else if(xhr.readyState === 4 && xhr.status !== 200){
                error && error(xhr.status);
            }
        }
        xhr.send();
    }

</script>
</html>